﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WarehouseManagement.Views.Merchandise;

namespace WarehouseManagement.Helper
{
    internal class ViewHelper
    {

        private ViewHelper() { }

        public static void LoadModule(string moduleName, Control container)
        {
            //moduleName = "SaleManagement.Views.Merchandise.MerchandiseListControl";

           
            var control = Activator.CreateInstance(Type.GetType(moduleName)) as Control;

            if (ModuleLoaded(moduleName, container))
            {
                return;
            }

            container.SuspendLayout();
            try
            {
                container.Controls.Clear();
                control.Dock = DockStyle.Fill;
                
                container.Controls.Add(control);
                //System.Threading.Thread.Sleep(500);
            }
            finally
            {
                container.ResumeLayout();
            }

        }

        public static bool ModuleLoaded(string moduleName, Control container)
        {
            foreach (Control c in container.Controls)
            {
                if (GetShortModuleName(c.Name) == GetShortModuleName(moduleName))
                    return true;
            }
            return false;

        }

        private static string GetShortModuleName(string fullModuleName)
        {
            if (!fullModuleName.Contains('.'))
                return fullModuleName;
            var pieces = fullModuleName.Split('.');
            return pieces.LastOrDefault();
        }
    }
}
